package org.lfs;


import org.lfs.buttons.ButtonEditor;
import org.lfs.buttons.ButtonRenderer;
import org.lfs.config.PopularProjects;
import org.lfs.config.PromptDatabase;
import org.lfs.domain.Prompt;
import org.lfs.operations.AIAnalysis;
import org.lfs.operations.FileOperations;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.io.*;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.stream.Collectors;



public class FileExplorer extends JFrame {
    private static final long serialVersionUID = 1L;

    public FileExplorer() {
        setTitle("一站式财富密码工具");
        setSize(400, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        // 设置 GridLayout，1列，按钮竖直排列
        setLayout(new GridLayout(0, 1, 10, 10));

        JButton btnGetPopularProjects = new JButton("获取热门项目");
//        btnGetPopularProjects.addActionListener(e -> PopularProjects.showPopularProjects());
        btnGetPopularProjects.addActionListener(e -> PopularProjects.showProjectSearchDialog());

        JButton btnSelectDirForCopy = new JButton("选择复制目录");
        btnSelectDirForCopy.addActionListener(e -> FileOperations.selectAndFlattenAndCopyFiles());

        JButton btnDeleteTestFiles = new JButton("清除测试类");
        btnDeleteTestFiles.addActionListener(e -> deleteTestFiles());

        JButton btnAIAnalysis = new JButton("AI分析");
        btnAIAnalysis.addActionListener(e -> AIAnalysis.openAIAnalysis());


        add(btnGetPopularProjects);
        add(btnSelectDirForCopy);
        add(btnDeleteTestFiles); // 添加删除测试类的按钮
        add(createExtractContentButton());
        add(createSelectPromptButton());
        add(btnAIAnalysis);
        add(createDrawingButton()); // 添加绘图按钮
        add(createGenerateDocumentButton()); // 添加生成文档按钮


        // 加载并设置自定义图标
        setCustomIcon();

        setLocationRelativeTo(null); // 将窗口居中显示
    }

    private void deleteTestFiles() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            File selectedDir = fileChooser.getSelectedFile();
            try {
                deleteFilesWithPattern(selectedDir);
                JOptionPane.showMessageDialog(this, "已清除测试代码");
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "删除文件时发生错误: " + ex.getMessage());
            }
        }
    }

    private void deleteFilesWithPattern(File dir) throws IOException {
        Files.walk(dir.toPath())
                .filter(Files::isRegularFile)
                .filter(path -> path.getFileName().toString().toLowerCase().contains("test"))
                .forEach(path -> {
                    try {
                        Files.delete(path);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
    }



    private JButton createGenerateDocumentButton() {
        JButton button = new JButton("生成文档");
        button.addActionListener(e -> showGenerateDocumentDialog());
        return button;
    }


    private void showGenerateDocumentDialog() {
        JDialog dialog = new JDialog(this, "输入内容", true);

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int widthMargin = screenSize.width / 12;
        int heightMargin = screenSize.height / 12;

        int dialogWidth = screenSize.width - 2 * widthMargin;
        int dialogHeight = screenSize.height - 2 * heightMargin;
        dialog.setSize(dialogWidth, dialogHeight);

        int componentMargin = dialogWidth / 30;

        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        contentPanel.setBorder(new EmptyBorder(componentMargin, componentMargin, componentMargin, componentMargin));

        String[] smallPlaceholders = {"姓名(工号)", "手机号", "邮箱", "标题"};
        JTextField[] smallFields = new JTextField[4];

        // 初始化小输入框
        for (int i = 0; i < smallPlaceholders.length; i++) {
            JTextField textField = new JTextField();
            addPlaceholder(textField, smallPlaceholders[i]);

            textField.setPreferredSize(new Dimension(dialogWidth - 2 * componentMargin, 30));
            textField.setBorder(new EmptyBorder(5, 5, 5, 5));

            contentPanel.add(textField);
            contentPanel.add(Box.createRigidArea(new Dimension(0, 10)));

            smallFields[i] = textField;  // 存储到smallFields数组
        }

        JTextArea[] textAreas = new JTextArea[8];
        String[] placeholders = {
                "技术领域",
                "现有技术（背景技术）",
                "背景技术的缺陷（本技术方案所要解决的技术问题）",
                "技术方案详述（核心撰写部分）",
                "本技术方案所产生的有益的技术效果",
                "本技术的关键点和想要进行专利保护的保护点",
                "可替代的技术方案",
                "其他需要补充的技术方案信息\n（如：专用名词的含义、英文缩略词的含义、引用文献、专利号码及文献出处等）"
        };

        for (int i = 0; i < placeholders.length; i++) {
            JTextArea textArea = new JTextArea(5, 50);
            textAreas[i] = textArea;  // 存储到textAreas数组
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            addPlaceholder(textArea, placeholders[i]);

            textArea.setPreferredSize(new Dimension(dialogWidth - 2 * componentMargin, 100));
            textArea.setBorder(new EmptyBorder(5, 5, 5, 5));

            JScrollPane scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            scrollPane.setBorder(new EmptyBorder(5, 5, 5, 5));

            contentPanel.add(scrollPane);
            contentPanel.add(Box.createRigidArea(new Dimension(0, 10)));
        }

        JScrollPane scrollPane = new JScrollPane(contentPanel);
        dialog.add(scrollPane, BorderLayout.CENTER);

        JButton submitButton = new JButton("【生成】");
        submitButton.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        submitButton.setForeground(Color.RED);
        submitButton.setPreferredSize(new Dimension(100, 50));
        submitButton.addActionListener(e -> {
            dialog.dispose();

            // 获取smallFields的文本内容，并排除占位符
            String[] smallContents = new String[smallFields.length];
            for (int i = 0; i < smallFields.length; i++) {
                smallContents[i] = smallFields[i].getText().isEmpty() || smallFields[i].getText().equals(smallPlaceholders[i])
                        ? "" : smallFields[i].getText();
            }


            // 获取textAreas的文本内容，并排除占位符
            String[] contents = new String[8];
            for (int i = 0; i < textAreas.length; i++) {
                String text = textAreas[i].getText().replaceAll("(?m)^[ \t]*\r?\n", "").replaceAll("\n{2,}", "\n").trim();
                contents[i] = text.isEmpty() || text.equals(placeholders[i])
                        ? "" : text;
            }

            new FileOperations().processMinioTemplate(smallContents,contents);
        });

        dialog.add(submitButton, BorderLayout.SOUTH);

        dialog.setLocation(widthMargin, heightMargin);
        dialog.setVisible(true);
    }





    private void addPlaceholder(JTextComponent textComponent, String placeholder) {
        textComponent.setText(placeholder);
        textComponent.setForeground(Color.GRAY);

        textComponent.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                if (textComponent.getText().equals(placeholder)) {
                    textComponent.setText("");
                    textComponent.setForeground(Color.BLACK);
                }
            }

            @Override
            public void focusLost(FocusEvent e) {
                if (textComponent.getText().isEmpty()) {
                    textComponent.setForeground(Color.GRAY);
                    textComponent.setText(placeholder);
                }
            }
        });
    }





    private void setCustomIcon() {
        try {
            // 确保图标文件放在合适的路径中
            ImageIcon icon = new ImageIcon("src/main/resources/image/logo.png");
            setIconImage(icon.getImage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private JButton createExtractContentButton() {
        JButton extractContentButton = new JButton("选择提取内容目录");
        extractContentButton.addActionListener(e -> {
            String[] options = {"Java", "Python", "JS相关"};

            String selectedOption = (String) JOptionPane.showInputDialog(
                    null,
                    "请选择提取内容类型",
                    "提取内容",
                    JOptionPane.PLAIN_MESSAGE,
                    null,
                    options,
                    options[0]
            );

            if (selectedOption != null) {
                switch (selectedOption) {
                    case "Java":
                        FileOperations.selectAndExtractContent("Java");
                        break;
                    case "Python":
                        FileOperations.selectAndExtractContent("Python");
                        break;
                    case "H5":
                        FileOperations.selectAndExtractContent("H5");
                        break;
                }
            }
        });
        return extractContentButton;
    }


    private JButton createSelectPromptButton() {
        JButton selectPromptButton = new JButton("选择提示词");
        selectPromptButton.addActionListener(e -> {
            // 创建一个模态对话框来显示加载中的信息
            JDialog loadingDialog = new JDialog(this, "加载中", true);

            // 创建一个 JPanel 并使用 BorderLayout，默认情况下CENTER是居中的
            JPanel panel = new JPanel(new BorderLayout());
            JLabel loadingLabel = new JLabel("数据库连接中，请稍候...", SwingConstants.CENTER);
            panel.add(loadingLabel, BorderLayout.CENTER);

            loadingDialog.add(panel);
            loadingDialog.setSize(200, 100);
            loadingDialog.setLocationRelativeTo(this);

            // 创建一个 SwingWorker 来执行耗时的数据库操作
            SwingWorker<List<Prompt>, Void> worker = new SwingWorker<List<Prompt>, Void>() {
                @Override
                protected List<Prompt> doInBackground() {
                    // 执行数据库查询
                    return PromptDatabase.getPromptsFromDatabase();
                }

                @Override
                protected void done() {
                    // 在完成后，隐藏或关闭加载对话框
                    loadingDialog.dispose();
                    try {
                        showPromptTable(get());
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, "无法加载提示词: " + ex.getMessage());
                    }
                }
            };

            // 在线程开始执行之前显示加载对话框
            SwingUtilities.invokeLater(() -> loadingDialog.setVisible(true));

            // 执行 SwingWorker
            worker.execute();
        });
        return selectPromptButton;
    }


    private static JButton createDrawingButton() {
        JButton drawingButton = new JButton("mermaid本地绘图");
        drawingButton.addActionListener(e -> {
            SwingWorker<File, Void> worker = new SwingWorker<File, Void>() {
                @Override
                protected File doInBackground() throws Exception {
                    // 加载资源并写入临时文件
                    InputStream inputStream = FileExplorer.class.getResourceAsStream("/html/mermaid-editor.html");
                    if (inputStream == null) {
                        throw new IOException("资源文件未找到: /html/mermaid-editor.html");
                    }
                    String htmlContent = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
                            .lines().collect(Collectors.joining("\n"));
                    File tempFile = File.createTempFile("mermaid-editor", ".html");
                    tempFile.deleteOnExit();
                    try (FileWriter writer = new FileWriter(tempFile)) {
                        writer.write(htmlContent);
                    }
                    return tempFile;
                }

                @Override
                protected void done() {
                    try {
                        File tempFile = get();
                        openBrowserExternally(tempFile.toURI().toString());
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, "操作失败: " + ex.getMessage());
                    }
                }
                private void openBrowserExternally(String url) {
                    new Thread(() -> {
                        try {
                            String os = System.getProperty("os.name").toLowerCase();
                            if (os.contains("win")) {
                                // Windows 系统
                                Runtime.getRuntime().exec(new String[]{"cmd", "/c", "start", url});
                            } else if (os.contains("mac")) {
                                // macOS 系统
                                Runtime.getRuntime().exec(new String[]{"open", url});
                            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                                // Linux 系统
                                Runtime.getRuntime().exec(new String[]{"xdg-open", url});
                            } else {
                                throw new UnsupportedOperationException("不支持的操作系统: " + os);
                            }
                        } catch (IOException e) {
                            SwingUtilities.invokeLater(() ->
                                    JOptionPane.showMessageDialog(null, "无法打开浏览器: " + e.getMessage())
                            );
                        }
                    }).start();
                }
            };
            worker.execute();
        });
        return drawingButton;
    }




    private void openDrawingTool() {
        try {
            Desktop.getDesktop().browse(new URI("https://www.min2k.com/tools/mermaid/"));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "无法打开浏览器: " + e.getMessage());
        }
    }



    private void showPromptTable(List<Prompt> prompts) {
        String[] columnNames = {"类型", "提示词", "点击复制"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0);

        for (Prompt prompt : prompts) {
            model.addRow(new Object[]{prompt.getType(), prompt.getText(), "复制"});
        }

        JTable table = new JTable(model) {
            public boolean isCellEditable(int row, int column) {
                return column == 2;
            }
        };

        // 设置自定义渲染器
        table.getColumn("类型").setCellRenderer(new CustomRenderer());

        // 隐藏提示词列（第二列，索引 1）
        table.getColumnModel().getColumn(1).setMinWidth(0);
        table.getColumnModel().getColumn(1).setMaxWidth(0);
        table.getColumnModel().getColumn(1).setWidth(0);


        table.getColumn("点击复制").setCellRenderer(new ButtonRenderer());
        table.getColumn("点击复制").setCellEditor(new ButtonEditor(new JCheckBox(), table));

        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setPreferredSize(new Dimension(600, 300));
        JOptionPane.showMessageDialog(null, scrollPane, "提示词选择", JOptionPane.INFORMATION_MESSAGE);
    }



    static class CustomRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (row == 0 && column == 0) {
                c.setForeground(Color.RED);  // 设置第一行第一列为红色
            } else {
                c.setForeground(Color.BLACK);
            }
            return c;
        }
    }
}